<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="mask-icon" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0" color="#222">





  <meta name="keywords" content="vps, java, python, golang, springmvc">




  


  <link rel="alternate" href="/atom.xml" title="张恒的网络日志" type="application/atom+xml">






<meta name="keywords" content="java, python, go, 技术, 学习笔记, spring">
<meta property="og:type" content="website">
<meta property="og:title" content="张恒的网络日志">
<meta property="og:url" content="http://blog.gavinzh.com/404.html">
<meta property="og:site_name" content="张恒的网络日志">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-05T08:52:36.912Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张恒的网络日志">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: true,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.gavinzh.com/404.html">





  <title>Guava学习：Cache缓存入门 | 张恒的网络日志</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98061925-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">张恒的网络日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Zhang Heng's WebSite Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.gavinzh.com/2016/10/27/guava-cache-study/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gavin Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/5567916">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="张恒的网络日志">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Guava学习：Cache缓存入门</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-10-27T08:35:00+00:00">2016-10-27</time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/笔记/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2016/10/27/guava-cache-study/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2016/10/27/guava-cache-study/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2016/10/27/guava-cache-study/" class="leancloud_visitors" data-flag-title="Guava学习：Cache缓存入门">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>摘要: 学习Google内部使用的工具包Guava，在Java项目中轻松地增加缓存，提高程序获取数据的效率。</p>
<a id="more"></a>

<h2 id="一、什么是缓存？"><a href="#一、什么是缓存？" class="headerlink" title="一、什么是缓存？"></a>一、什么是缓存？</h2><p>根据科普中国的定义，<code>缓存就是数据交换的缓冲区（称作Cache）</code>，当某一硬件要读取数据时，会首先从缓存中查找需要的数据，如果找到了则直接执行，找不到的话则从内存中找。由于缓存的运行速度比内存快得多，故缓存的作用就是帮助硬件更快地运行。</p>
<p>在这里，我们借用了硬件缓存的概念，当在Java程序中计算或查询数据的代价很高，并且对同样的计算或查询条件需要不止一次获取数据的时候，就应当考虑使用缓存。换句话说，缓存就是以空间换时间，大部分应用在各种IO，数据库查询等耗时较长的应用当中。</p>
<h2 id="二、缓存原理"><a href="#二、缓存原理" class="headerlink" title="二、缓存原理"></a>二、缓存原理</h2><p>当获取数据时，程序将先从一个存储在内存中的数据结构中获取数据。如果数据不存在，则在磁盘或者数据库中获取数据并存入到数据结构当中。之后程序需要再次获取数据时，则会先查询这个数据结构。从内存中获取数据时间明显小于通过IO获取数据，这个数据结构就是缓存的实现。</p>
<p>这里引入一个概念，缓存<code>命中率</code>：从缓存中获取到数据的次数/全部查询次数，命中率越高说明这个缓存的效率好。由于机器内存的限制，缓存一般只能占据有限的内存大小，缓存需要不定期的删除一部分数据，从而保证不会占据大量内存导致机器崩溃。</p>
<p>如何提高命中率呢？那就得从删除一部分数据着手了。目前有三种删除数据的方式，分别是：<code>FIFO（先进先出）</code>、<code>LFU（定期淘汰最少使用次数）</code>、<code>LRU（淘汰最长时间未被使用）</code>。</p>
<h2 id="三、GuavaCache工作方式"><a href="#三、GuavaCache工作方式" class="headerlink" title="三、GuavaCache工作方式"></a>三、GuavaCache工作方式</h2><p>GuavaCache的<strong>工作流程</strong>：<code>获取数据-&gt;如果存在，返回数据-&gt;计算获取数据-&gt;存储返回</code>。由于特定的工作流程，使用者必须在创建Cache或者获取数据时指定不存在数据时应当怎么获取数据。GuavaCache采用LRU的工作原理，使用者必须指定缓存数据的大小，当超过缓存大小时，必定引发数据删除。GuavaCache还可以让用户指定缓存数据的过期时间，刷新时间等等很多有用的功能。</p>
<h2 id="四、GuavaCache使用Demo"><a href="#四、GuavaCache使用Demo" class="headerlink" title="四、GuavaCache使用Demo"></a>四、GuavaCache使用Demo</h2><h3 id="4-1-简单使用"><a href="#4-1-简单使用" class="headerlink" title="4.1 简单使用"></a>4.1 简单使用</h3><p>有人说我就想简简单单的使用cache，就像Map那样方便就行。接下来展示一段简单的使用方式。</p>
<p>首先定义一个需要存储的Bean，对象Man：</p>
<pre><code>/**
 * @author jiangmitiao
 * @version V1.0
 * @Title: 标题
 * @Description: Bean
 * @date 2016/10/27 10:01
 */
public class Man {
    //身份证号
    private String id;
    //姓名
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return &quot;Man{&quot; +
                &quot;id=&apos;&quot; + id + &apos;\&apos;&apos; +
                &quot;, name=&apos;&quot; + name + &apos;\&apos;&apos; +
                &apos;}&apos;;
    }
}</code></pre><p>接下来我们写一个Demo：</p>
<pre><code>import com.google.common.cache.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;


/**
 * @author jiangmitiao
 * @version V1.0
 * @Description: Demo
 * @date 2016/10/27 10:00
 */
public class GuavaCachDemo {
    private LoadingCache&lt;String,Man&gt; loadingCache;

    //loadingCache
    public void InitLoadingCache() {
        //指定一个如果数据不存在获取数据的方法
        CacheLoader&lt;String, Man&gt; cacheLoader = new CacheLoader&lt;String, Man&gt;() {
            @Override
            public Man load(String key) throws Exception {
                //模拟mysql操作
                Logger logger = LoggerFactory.getLogger(&quot;LoadingCache&quot;);
                logger.info(&quot;LoadingCache测试 从mysql加载缓存ing...(2s)&quot;);
                Thread.sleep(2000);
                logger.info(&quot;LoadingCache测试 从mysql加载缓存成功&quot;);
                Man tmpman = new Man();
                tmpman.setId(key);
                tmpman.setName(&quot;其他人&quot;);
                if (key.equals(&quot;001&quot;)) {
                    tmpman.setName(&quot;张三&quot;);
                    return tmpman;
                }
                if (key.equals(&quot;002&quot;)) {
                    tmpman.setName(&quot;李四&quot;);
                    return tmpman;
                }
                return tmpman;
            }
        };
        //缓存数量为1，为了展示缓存删除效果
        loadingCache = CacheBuilder.newBuilder().maximumSize(1).build(cacheLoader);
    }
    //获取数据，如果不存在返回null
    public Man getIfPresentloadingCache(String key){
        return loadingCache.getIfPresent(key);
    }
    //获取数据，如果数据不存在则通过cacheLoader获取数据，缓存并返回
    public Man getCacheKeyloadingCache(String key){
        try {
            return loadingCache.get(key);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
    //直接向缓存put数据
    public void putloadingCache(String key,Man value){
        Logger logger = LoggerFactory.getLogger(&quot;LoadingCache&quot;);
        logger.info(&quot;put key :{} value : {}&quot;,key,value.getName());
        loadingCache.put(key,value);
    }
}</code></pre><p>接下来，我们写一些测试方法，检测一下</p>
<pre><code>public class Test {
    public static void main(String[] args){
        GuavaCachDemo cachDemo = new GuavaCachDemo()
        System.out.println(&quot;使用loadingCache&quot;);
        cachDemo.InitLoadingCache();

        System.out.println(&quot;使用loadingCache get方法  第一次加载&quot;);
        Man man = cachDemo.getCacheKeyloadingCache(&quot;001&quot;);
        System.out.println(man);

        System.out.println(&quot;\n使用loadingCache getIfPresent方法  第一次加载&quot;);
        man = cachDemo.getIfPresentloadingCache(&quot;002&quot;);
        System.out.println(man);

        System.out.println(&quot;\n使用loadingCache get方法  第一次加载&quot;);
        man = cachDemo.getCacheKeyloadingCache(&quot;002&quot;);
        System.out.println(man);

        System.out.println(&quot;\n使用loadingCache get方法  已加载过&quot;);
        man = cachDemo.getCacheKeyloadingCache(&quot;002&quot;);
        System.out.println(man);

        System.out.println(&quot;\n使用loadingCache get方法  已加载过,但是已经被剔除掉,验证重新加载&quot;);
        man = cachDemo.getCacheKeyloadingCache(&quot;001&quot;);
        System.out.println(man);

        System.out.println(&quot;\n使用loadingCache getIfPresent方法  已加载过&quot;);
        man = cachDemo.getIfPresentloadingCache(&quot;001&quot;);
        System.out.println(man);

        System.out.println(&quot;\n使用loadingCache put方法  再次get&quot;);
        Man newMan = new Man();
        newMan.setId(&quot;001&quot;);
        newMan.setName(&quot;额外添加&quot;);
        cachDemo.putloadingCache(&quot;001&quot;,newMan);
        man = cachDemo.getCacheKeyloadingCache(&quot;001&quot;);
        System.out.println(man);
    }
}</code></pre><p>测试结果如下：</p>
<p><img src="/images/pasted-29.png" alt="upload successful"></p>
<h3 id="4-2-高级特性"><a href="#4-2-高级特性" class="headerlink" title="4.2 高级特性"></a>4.2 高级特性</h3><pre><code>由于目前使用有局限性，接下来只讲我用到的一些方法。</code></pre><p>我来演示一下GuavaCache自带的两个Cache</p>
<pre><code>GuavaCacheDemo.java

import com.google.common.cache.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;


/**
 * @author jiangmitiao
 * @version V1.0
 * @Description: Demo
 * @date 2016/10/27 10:00
 */
public class GuavaCachDemo {
    private Cache&lt;String, Man&gt; cache;
    private LoadingCache&lt;String,Man&gt; loadingCache;
    private RemovalListener&lt;String, Man&gt; removalListener;

    public void Init(){
        //移除key-value监听器
        removalListener = new RemovalListener&lt;String, Man&gt;(){
            public void onRemoval(RemovalNotification&lt;String, Man&gt; notification) {
                Logger logger = LoggerFactory.getLogger(&quot;RemovalListener&quot;);
                logger.info(notification.getKey()+&quot;被移除&quot;);
                //可以在监听器中获取key,value,和删除原因
                notification.getValue();
                notification.getCause();//EXPLICIT、REPLACED、COLLECTED、EXPIRED、SIZE

            }};
        //可以使用RemovalListeners.asynchronous方法将移除监听器设为异步方法
        //removalListener = RemovalListeners.asynchronous(removalListener, new ThreadPoolExecutor(1,1,1000, TimeUnit.MINUTES,new ArrayBlockingQueue&lt;Runnable&gt;(1)));
    }

    //loadingCache
    public void InitLoadingCache() {
        //指定一个如果数据不存在获取数据的方法
        CacheLoader&lt;String, Man&gt; cacheLoader = new CacheLoader&lt;String, Man&gt;() {
            @Override
            public Man load(String key) throws Exception {
                //模拟mysql操作
                Logger logger = LoggerFactory.getLogger(&quot;LoadingCache&quot;);
                logger.info(&quot;LoadingCache测试 从mysql加载缓存ing...(2s)&quot;);
                Thread.sleep(2000);
                logger.info(&quot;LoadingCache测试 从mysql加载缓存成功&quot;);
                Man tmpman = new Man();
                tmpman.setId(key);
                tmpman.setName(&quot;其他人&quot;);
                if (key.equals(&quot;001&quot;)) {
                    tmpman.setName(&quot;张三&quot;);
                    return tmpman;
                }
                if (key.equals(&quot;002&quot;)) {
                    tmpman.setName(&quot;李四&quot;);
                    return tmpman;
                }
                return tmpman;
            }
        };
        //缓存数量为1，为了展示缓存删除效果
        loadingCache = CacheBuilder.newBuilder().
                //设置2分钟没有获取将会移除数据
                expireAfterAccess(2, TimeUnit.MINUTES).
                //设置2分钟没有更新数据则会移除数据
                expireAfterWrite(2, TimeUnit.MINUTES).
                //每1分钟刷新数据
                refreshAfterWrite(1,TimeUnit.MINUTES).
                //设置key为弱引用
                weakKeys().
//                weakValues().//设置存在时间和刷新时间后不能再次设置
//                softValues().//设置存在时间和刷新时间后不能再次设置
                maximumSize(1).
                removalListener(removalListener).
                build(cacheLoader);
    }

    //获取数据，如果不存在返回null
    public Man getIfPresentloadingCache(String key){
        return loadingCache.getIfPresent(key);
    }

    //获取数据，如果数据不存在则通过cacheLoader获取数据，缓存并返回
    public Man getCacheKeyloadingCache(String key){
        try {
            return loadingCache.get(key);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    //直接向缓存put数据
    public void putloadingCache(String key,Man value){
        Logger logger = LoggerFactory.getLogger(&quot;LoadingCache&quot;);
        logger.info(&quot;put key :{} value : {}&quot;,key,value.getName());
        loadingCache.put(key,value);
    }

    public void InitDefault() {
        cache = CacheBuilder.newBuilder().
                expireAfterAccess(2, TimeUnit.MINUTES).
                expireAfterWrite(2, TimeUnit.MINUTES).
//                refreshAfterWrite(1,TimeUnit.MINUTES).//没有cacheLoader的cache不能设置刷新，因为没有指定获取数据的方式
                weakKeys().
//                weakValues().//设置存在时间和刷新时间后不能再次设置
//                softValues().//设置存在时间和刷新时间后不能再次设置
                maximumSize(1).
                removalListener(removalListener).
                build();
    }

    public Man getIfPresentCache(String key){
        return cache.getIfPresent(key);
    }
    public Man getCacheKeyCache(final String key) throws ExecutionException {
        return cache.get(key, new Callable&lt;Man&gt;() {
            public Man call() throws Exception {
                //模拟mysql操作
                Logger logger = LoggerFactory.getLogger(&quot;Cache&quot;);
                logger.info(&quot;Cache测试 从mysql加载缓存ing...(2s)&quot;);
                Thread.sleep(2000);
                logger.info(&quot;Cache测试 从mysql加载缓存成功&quot;);
                Man tmpman = new Man();
                tmpman.setId(key);
                tmpman.setName(&quot;其他人&quot;);
                if (key.equals(&quot;001&quot;)) {
                    tmpman.setName(&quot;张三&quot;);
                    return tmpman;
                }
                if (key.equals(&quot;002&quot;)) {
                    tmpman.setName(&quot;李四&quot;);
                    return tmpman;
                }
                return tmpman;
            }
        });
    }

    public void putCache(String key,Man value){
        Logger logger = LoggerFactory.getLogger(&quot;Cache&quot;);
        logger.info(&quot;put key :{} value : {}&quot;,key,value.getName());
        cache.put(key,value);
    }
}</code></pre><p>在这个demo中，分别采用了Guava自带的两个Cache：LocalLoadingCache和LocalManualCache。并且添加了监听器，当数据被删除后会打印日志。</p>
<p>Main：</p>
<pre><code>public static void main(String[] args){
    GuavaCachDemo cachDemo = new GuavaCachDemo();
    cachDemo.Init();

    System.out.println(&quot;使用loadingCache&quot;);
    cachDemo.InitLoadingCache();

    System.out.println(&quot;使用loadingCache get方法  第一次加载&quot;);
    Man man = cachDemo.getCacheKeyloadingCache(&quot;001&quot;);
    System.out.println(man);

    System.out.println(&quot;\n使用loadingCache getIfPresent方法  第一次加载&quot;);
    man = cachDemo.getIfPresentloadingCache(&quot;002&quot;);
    System.out.println(man);

    System.out.println(&quot;\n使用loadingCache get方法  第一次加载&quot;);
    man = cachDemo.getCacheKeyloadingCache(&quot;002&quot;);
    System.out.println(man);

    System.out.println(&quot;\n使用loadingCache get方法  已加载过&quot;);
    man = cachDemo.getCacheKeyloadingCache(&quot;002&quot;);
    System.out.println(man);

    System.out.println(&quot;\n使用loadingCache get方法  已加载过,但是已经被剔除掉,验证重新加载&quot;);
    man = cachDemo.getCacheKeyloadingCache(&quot;001&quot;);
    System.out.println(man);

    System.out.println(&quot;\n使用loadingCache getIfPresent方法  已加载过&quot;);
    man = cachDemo.getIfPresentloadingCache(&quot;001&quot;);
    System.out.println(man);

    System.out.println(&quot;\n使用loadingCache put方法  再次get&quot;);
    Man newMan = new Man();
    newMan.setId(&quot;001&quot;);
    newMan.setName(&quot;额外添加&quot;);
    cachDemo.putloadingCache(&quot;001&quot;,newMan);
    man = cachDemo.getCacheKeyloadingCache(&quot;001&quot;);
    System.out.println(man);

    ///////////////////////////////////
    System.out.println(&quot;\n\n使用Cache&quot;);
    cachDemo.InitDefault();

    System.out.println(&quot;使用Cache get方法  第一次加载&quot;);
    try {
        man = cachDemo.getCacheKeyCache(&quot;001&quot;);
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    System.out.println(man);

    System.out.println(&quot;\n使用Cache getIfPresent方法  第一次加载&quot;);
    man = cachDemo.getIfPresentCache(&quot;002&quot;);
    System.out.println(man);

    System.out.println(&quot;\n使用Cache get方法  第一次加载&quot;);
    try {
        man = cachDemo.getCacheKeyCache(&quot;002&quot;);
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    System.out.println(man);

    System.out.println(&quot;\n使用Cache get方法  已加载过&quot;);
    try {
        man = cachDemo.getCacheKeyCache(&quot;002&quot;);
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    System.out.println(man);

    System.out.println(&quot;\n使用Cache get方法  已加载过,但是已经被剔除掉,验证重新加载&quot;);
    try {
        man = cachDemo.getCacheKeyCache(&quot;001&quot;);
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    System.out.println(man);

    System.out.println(&quot;\n使用Cache getIfPresent方法  已加载过&quot;);
    man = cachDemo.getIfPresentCache(&quot;001&quot;);
    System.out.println(man);

    System.out.println(&quot;\n使用Cache put方法  再次get&quot;);
    Man newMan1 = new Man();
    newMan1.setId(&quot;001&quot;);
    newMan1.setName(&quot;额外添加&quot;);
    cachDemo.putloadingCache(&quot;001&quot;,newMan1);
    man = cachDemo.getCacheKeyloadingCache(&quot;001&quot;);
    System.out.println(man);
}</code></pre><p>测试结果如下：</p>
<p><img src="/images/pasted-30.png" alt="upload successful"></p>
<p><img src="/images/pasted-31.png" alt="upload successful"></p>
<p>由上述结果可以表明，GuavaCache可以在数据存储到达指定大小后删除数据结构中的数据。我们可以<strong>设置定期删除而达到定期从数据库、磁盘等其他地方更新数据</strong>等（再次访问时数据不存在重新获取）。也可以采用<strong>定时刷新的方式更新数据</strong>。</p>
<p>还可以设置移除监听器对被删除的数据进行一些操作。通过<code>RemovalListeners.asynchronous(RemovalListener,Executor)</code>方法将监听器设为异步，笔者通过实验发现，异步监听不会在删除数据时立刻调用监听器方法。</p>
<h2 id="五、GuavaCache结构初探"><a href="#五、GuavaCache结构初探" class="headerlink" title="五、GuavaCache结构初探"></a>五、GuavaCache结构初探</h2><p><img src="/images/pasted-32.png" alt="upload successful"></p>
<p>类结构图</p>
<p>GuavaCache并不希望我们设置复杂的参数，而让我们采用<code>建造者模式</code>创建Cache。GuavaCache分为两种Cache:<code>Cache</code>，<code>LoadingCache</code>。LoadingCache继承了Cache，他比Cache主要多了get和refresh方法。多这两个方法能干什么呢？</p>
<p>在第四节高级特性demo中，我们看到builder生成不带CacheLoader的Cache实例。在类结构图中其实是生成了<code>LocalManualCache</code>类实例。而带CacheLoader的Cache实例生成的是<code>LocalLoadingCache</code>。他可以定时刷新数据，因为<strong>获取数据的方法已经作为构造参数方法存入了Cache实例中</strong>。同样，在get时，不需要像LocalManualCache还需要传入一个Callable实例。</p>
<p>实际上，这两个Cache实现类都继承自<code>LocalCache</code>，大部分实现都是父类做的。</p>
<h2 id="六、总结回顾"><a href="#六、总结回顾" class="headerlink" title="六、总结回顾"></a>六、总结回顾</h2><p>缓存加载：CacheLoader、Callable、显示插入(put)</p>
<p>缓存回收：LRU，定时(<code>expireAfterAccess</code>，<code>expireAfterWrite</code>)，软弱引用，显示删除(Cache接口方法<code>invalidate</code>，<code>invalidateAll</code>)</p>
<p>监听器：<code>CacheBuilder.removalListener(RemovalListener)</code></p>
<p>清理缓存时间：只有在获取数据时才或清理缓存LRU，使用者可以单起线程采用<code>Cache.cleanUp()</code>方法主动清理。</p>
<p>刷新：主动刷新方法<code>LoadingCache.referesh(K)</code></p>
<p>信息统计：<code>CacheBuilder.recordStats()</code> 开启Guava Cache的统计功能。<code>Cache.stats()</code>返回CacheStats对象。（其中包括命中率等相关信息）</p>
<p>获取当前缓存所有数据：<code>cache.asMap()</code>，cache.asMap().get(Object)会刷新数据的访问时间（影响的是：创建时设置的在多久没访问后删除数据）</p>
<h3 id="LocalManualCache和LocalLoadingCache的选择"><a href="#LocalManualCache和LocalLoadingCache的选择" class="headerlink" title="LocalManualCache和LocalLoadingCache的选择"></a>LocalManualCache和LocalLoadingCache的选择</h3><p><code>ManualCache</code>可以在get时动态设置获取数据的方法，而<code>LoadingCache</code>可以定时刷新数据。如何取舍？我认为在缓存数据有很多种类的时候采用第一种cache。而数据单一，数据库数据会定时刷新时采用第二种cache。</p>
<p>具体工程中的情况也欢迎大家与我交流，互相学习。</p>
<h3 id="参考资料："><a href="#参考资料：" class="headerlink" title="参考资料："></a>参考资料：</h3><p><a href="http://www.cnblogs.com/peida/p/Guava_Cache.html" target="_blank" rel="noopener">http://www.cnblogs.com/peida/p/Guava_Cache.html</a></p>
<p><a href="https://github.com/tiantiangao/guava-study/blob/master/doc/caches.md" target="_blank" rel="noopener">https://github.com/tiantiangao/guava-study/blob/master/doc/caches.md</a></p>
<p><a href="http://www.blogjava.net/DLevin/archive/2013/10/20/404847.html" target="_blank" rel="noopener">http://www.blogjava.net/DLevin/archive/2013/10/20/404847.html</a></p>
<p><a href="http://ifeve.com/google-guava-cachesexplained/" target="_blank" rel="noopener">http://ifeve.com/google-guava-cachesexplained/</a></p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Gavin Zhang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.gavinzh.com/2016/10/27/guava-cache-study/" title="Guava学习：Cache缓存入门">http://blog.gavinzh.com/2016/10/27/guava-cache-study/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/Guava/" rel="tag"># Guava</a>
          
            <a href="/tags/GuavaCache/" rel="tag"># GuavaCache</a>
          
            <a href="/tags/Cache/" rel="tag"># Cache</a>
          
            <a href="/tags/Builder/" rel="tag"># Builder</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/17/nginx-https/" rel="next" title="nginx代理+https设置">
                <i class="fa fa-chevron-left"></i> nginx代理+https设置
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/11/01/maven-javaweb-more-model/" rel="prev" title="Maven JavaWeb项目完全拆分方案">
                Maven JavaWeb项目完全拆分方案 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://avatars3.githubusercontent.com/u/5567916" alt="Gavin Zhang">
            
              <p class="site-author-name" itemprop="name">Gavin Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">158</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/jiangmitiao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:me at gavinzh.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、什么是缓存？"><span class="nav-number">1.</span> <span class="nav-text">一、什么是缓存？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、缓存原理"><span class="nav-number">2.</span> <span class="nav-text">二、缓存原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、GuavaCache工作方式"><span class="nav-number">3.</span> <span class="nav-text">三、GuavaCache工作方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、GuavaCache使用Demo"><span class="nav-number">4.</span> <span class="nav-text">四、GuavaCache使用Demo</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-简单使用"><span class="nav-number">4.1.</span> <span class="nav-text">4.1 简单使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-高级特性"><span class="nav-number">4.2.</span> <span class="nav-text">4.2 高级特性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五、GuavaCache结构初探"><span class="nav-number">5.</span> <span class="nav-text">五、GuavaCache结构初探</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#六、总结回顾"><span class="nav-number">6.</span> <span class="nav-text">六、总结回顾</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#LocalManualCache和LocalLoadingCache的选择"><span class="nav-number">6.1.</span> <span class="nav-text">LocalManualCache和LocalLoadingCache的选择</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考资料："><span class="nav-number">6.2.</span> <span class="nav-text">参考资料：</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2013 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gavin Zhang</span>

  

  
</div>





<div>
	<a href="http://www.beian.miit.gov.cn/" target="_blank">陕ICP备17010002号-1</a>
</div>





        




  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61868582";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261805793&web_id=1261805793" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>





  



  






  













  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fastclick/1.0.6/fastclick.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhang-hengs-website-blog.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.gavinzh.com/2016/10/27/guava-cache-study/';
          this.page.identifier = '2016/10/27/guava-cache-study/';
          this.page.title = 'Guava学习：Cache缓存入门';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhang-hengs-website-blog.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EhAMmIXTRGtethTcgYwA9afH-gzGzoHsz", "jzP1TaBhMleAUgPLXyB0h8oQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.0.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.0.0"></script>


  

</body>
</html>
